export default defineEventHandler(async (event) => {
  const query = getQuery(event);
  const { city, location } = query;
  
  // 高德地图API密钥
  const AMAP_KEY = 'ea14acfbeff3ab37b1a0ac893135a7e8';
  
  try {
    let weatherData;
    
    if (location) {
      // 使用坐标获取天气
      const [lng, lat] = (location as string).split(',').map(Number);
      const response = await fetch(
        `https://restapi.amap.com/v3/weather/weatherInfo?key=${AMAP_KEY}&city=${lng},${lat}&extensions=all&output=json`
      );
      weatherData = await response.json();
    } else if (city) {
      // 使用城市名获取天气
      const response = await fetch(
        `https://restapi.amap.com/v3/weather/weatherInfo?key=${AMAP_KEY}&city=${city}&extensions=all&output=json`
      );
      weatherData = await response.json();
    } else {
      throw createError({
        statusCode: 400,
        statusMessage: '缺少必要参数：city 或 location'
      });
    }
    
    if (weatherData.status === '1') {
      return {
        success: true,
        data: weatherData.forecasts || weatherData.lives,
        message: '获取天气信息成功'
      };
    } else {
      throw createError({
        statusCode: 500,
        statusMessage: `天气API错误: ${weatherData.info}`
      });
    }
  } catch (error) {
    console.error('天气API调用失败:', error);
    throw createError({
      statusCode: 500,
      statusMessage: '获取天气信息失败'
    });
  }
}); 